<?php

class Boxcategoryslide extends Module {

	private $_pageHtml = '';

	

	public function __construct() {

		$this->name = 'boxcategoryslide';
		$this->tab = 'front_office_features';
		$this->author = 'nguyentn';
		$this->version = 1.2;
		$this->need_instance = 0;
		
		parent::__construct();
		
		$this->displayName = $this->l('Box slideshow image for list category');
		$this->description = $this->l('Box slideshow image for list category.');
		$this->_pageHtml='<h2>'.$this->displayName.'</h2>';
	}

	public function install() {
		Db::getInstance()->Execute('
		CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.'boxcategoryparent (
			`idparent` int(11) NOT NULL AUTO_INCREMENT,
			`name` varchar(255) NOT NULL,
			`listidcat` varchar(255) NULL,
			PRIMARY KEY(`idparent`)
		);
		CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.'boxcategorychild (
			`idchild` int(11) NOT NULL AUTO_INCREMENT,
			`idparent` int(11) NOT NULL,
			`urlimg` varchar(255) NOT NULL,
			`listidcat` varchar(255) NOT NULL,
			PRIMARY KEY(`idchild`)
		);');
		return (parent::install() AND $this->registerHook('home') AND $this->registerHook('header'));
	}

	public function uninstall() {
		Db::getInstance()->Execute('DROP TABLE '._DB_PREFIX_.'boxcategoryparent; DROP TABLE '._DB_PREFIX_.'boxcategorychild;');
		return parent::uninstall();
	}

	private function recurseCategory($categories, $current, $id_category = 2, $id_category_default = 2)
	{
		global $done;
		static $irow;
		if (!isset($done[$current['infos']['id_parent']]))
			$done[$current['infos']['id_parent']] = 0;
		$done[$current['infos']['id_parent']] += 1;

		$todo = sizeof($categories[$current['infos']['id_parent']]);
		$doneC = $done[$current['infos']['id_parent']];

		$level = $current['infos']['level_depth'] + 1;
		$img = $level == 1 ? 'lv1.png' : 'lv'.$level.'_'.($todo == $doneC ? 'f' : 'b').'.png';

		$this->_pageHtml .= '
		<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
			<td>
				<input type="checkbox" name="categoryBox[]" class="categoryBox'.($id_category_default != NULL ? ' id_category_default' : '').'" id="categoryBox_'.$id_category.'" value="'.$id_category.'" />
			</td>
			<td>
				'.$id_category.'
			</td>
			<td>
				<img src="../img/admin/'.$img.'" alt="" /> &nbsp;<label for="categoryBox_'.$id_category.'" class="t">'.stripslashes(Category::hideCategoryPosition($current['infos']['name'])).'</label>
			</td>
		</tr>';

		if (isset($categories[$id_category]))
			foreach ($categories[$id_category] AS $key => $row)
				if ($key != 'infos')
					$this->recurseCategory($categories, $categories[$id_category][$key], $key, NULL);
	}

  	public function getContent()
  	{
	    global $cookie;
	  	$categories = Category::getCategories(intval($cookie->id_lang), false);
		$this->_pageHtml .='<script type="text/javascript" src="'.__PS_BASE_URI__.'js/jquery/jquery.tablednd_0_5.js"></script>
				<script type="text/javascript">
					var token = \''.Tools::getValue('token').'\';
					var come_from = \'blockimagepromo\';
					var alternate = \'0\';
				</script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/admin-dnd.js"></script>' .
		'<form method="post" action="'.$_SERVER['REQUEST_URI'].'" name="FormCustomersDiscount" id="FormCustomersDiscount">';
		if (Tools::isSubmit('submitAddParent'))
		{
			if(Tools::getValue('categoryBox') && Tools::getValue('name'))
			{
				$sql='INSERT INTO '._DB_PREFIX_.'boxcategoryparent (name,listidcat)'.
				" VALUES('".Tools::getValue('name')."','".implode(',',Tools::getValue('categoryBox'))."')";
				Db::getInstance()->Execute($sql);
			}
			else
				$this->_pageHtml  .= '<div class="error"><img src="../img/admin/error2.png">'.$this->l('You not select categories').'</div>';
		}
		
		//delete child
		if(Tools::getValue('idparent') && Tools::getValue('view') || Tools::isSubmit('submitAddChild'))
		{
			//$this->_pageHtml.='<a href="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'">Back</a>';
			if(Tools::getValue('idchild') && Tools::getValue('deletechild'))
			{
				$sql='DELETE FROM '._DB_PREFIX_.'boxcategorychild WHERE idchild='.Tools::getValue('idchild');
				Db::getInstance()->Execute($sql);
			}
			if (Tools::isSubmit('submitAddChild'))
			{
				if(Tools::getValue('urlimg'))
				{
					$sql='INSERT INTO '._DB_PREFIX_.'boxcategorychild (idparent,urlimg)'.
					" VALUES(".Tools::getValue('idparent').",'".Tools::getValue('urlimg')."')";
					Db::getInstance()->Execute($sql);
				}
				else
					$this->_pageHtml  .= '<div class="error"><img src="../img/admin/error2.png">'.$this->l('You not select image').'</div>';
			}
			$this->_pageHtml .=$this->_getListChild();
			$this->_pageHtml.='<label>'.$this->l('Image :').'</label><div class="margin-form"><input name="urlimg" id="urlimg" value="" size="80" readonly="readonly"/> <button onclick="return setFile(\'urlimg\');" class="button">'.$this->l('Browse').'</button></div>'.
				'<div class="margin-form"><input type="submit" value="'.$this->l('   Save   ').'" name="submitAddChild" class="button" /></div>';
			$this->_pageHtml.='</form>';
			$iso = Language::getIsoById((int)($cookie->id_lang));
			$isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
			$ad = dirname($_SERVER["PHP_SELF"]);
			$this->_pageHtml.= '
				<script type="text/javascript">	
				var iso = \''.$isoTinyMCE.'\' ;
				var pathCSS = \''._THEME_CSS_DIR_.'\' ;
				var ad = \''.$ad.'\' ;
				</script>
				<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js"></script>
				<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce.inc.js"></script>'.
				"<script type=\"text/javascript\">
						function setFile(field_name) {
							var win = window.open(ad+'/ajaxfilemanager/ajaxfilemanager.php?editor=form&elementId='+field_name, 'ajaxFileImageManager', 'width=782,height=500');
							return false;
						}
				</script>
				";
			return $this->displayForm();
			
		}
		//delete parent
		if(Tools::getValue('id_slideshowcategory'))
		{
			$sql='DELETE FROM '._DB_PREFIX_.'boxcategorychild WHERE idparent='.Tools::getValue('id_slideshowcategory');
			Db::getInstance()->Execute($sql);
			$sql='DELETE FROM '._DB_PREFIX_.'boxcategoryparent WHERE idparent='.Tools::getValue('id_slideshowcategory');
			Db::getInstance()->Execute($sql);
		}
		
		$this->_pageHtml .=$this->_getListParent();	
		$this->_pageHtml .='<div style="height: 30px;">&nbsp;</div>';	
		$this->_pageHtml .='<label>'.$this->l('Group Name:').' </label>
				<div class="margin-form">
					<input type="text" name="name" value="" size="80" />
					<p style="clear: both;">'.$this->l('Name of group').'</p>
				</div>
				<div class="margin-form"><input type="submit" value="'.$this->l('   Save   ').'" name="submitAddParent" class="button" /></div>'.
			'<label>'.$this->l('Categories:').' </label>
			<div class="margin-form">
				<table cellspacing="0" cellpadding="0" class="table" width="100%">
					<tr>
						<th width="20"><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'categoryBox[]\', this.checked)" /></th>
						<th width="20">'.$this->l('ID').'</th>
						<th>'.$this->l('Name').'</th>
					</tr>';
					$this->recurseCategory($categories, $categories[0][1], 1, $obj->id);
		$this->_pageHtml .='</table>'.
			'</div>
		</form>';
		return $this->displayForm();
  	}

	public function displayForm()
	{
		return $this->_pageHtml;
	}
	
	private function _getListParent()
	{
		global $cookie;
		$result=$this->_getData();
		foreach($result as $key => $value)
		{
			$sql='SELECT name FROM '._DB_PREFIX_.'category_lang WHERE id_category IN ('.$value['listidcat'].') AND id_lang='.$cookie->id_lang;
			$listName=Db::getInstance()->ExecuteS($sql);
			$arrName=array();
			foreach($listName as $name)
				$arrName[]=$name['name'];
			$result[$key]['category']=implode(',',$arrName);
		}
		
		$html='<table cellspacing="0" cellpadding="0" class="table tableDnD" style="width: 100%;">
			<thead>
				<tr class="nodrag nodrop">
					<th style="width: 5%"><input type="checkbox" onclick="checkDelBoxes(this.form, \'id[]\', this.checked)" class="noborder" name="checkme">		</th>
					<th style="width: 10%">'.$this->l('Name Group').'</th>
					<th style="width: 50%">'.$this->l('Category').'</th>
					<th style="width: 10%">'.$this->l('Action').'</th>
				</tr>
			</thead>
			<tbody>';
		foreach($result as $item)
		{
			$html.='<tr>
						<td class="center"><input type="checkbox" class="noborder" value="'.$item['idparent'].'" name="id[]"></td>
						<td><a href="'.Tools::safeOutput($_SERVER['REQUEST_URI'].'&idparent='.$item['idparent']).'&view=1">'.$item['name'].'</a></td>
						<td >'.$item['category'].'</td>
						<td><a href="'.Tools::safeOutput($_SERVER['REQUEST_URI'].'&id_slideshowcategory='.$item['idparent']).'"><img title="Supprimer" alt="Supprimer" src="../img/admin/delete.gif"></a></td>
					</tr>';
		}
		$html.='</tbody></table>';
		return $html;
	}
	
	private function _getListChild()
	{
		global $cookie;
		$idparent=Tools::getValue('idparent');
		$result=$this->_getDataChild($idparent);
		
		$html='<table cellspacing="0" cellpadding="0" class="table tableDnD" style="width: 100%;">
			<thead>
				<tr class="nodrag nodrop">
					<th style="width: 5%"><input type="checkbox" onclick="checkDelBoxes(this.form, \'id[]\', this.checked)" class="noborder" name="checkme">		</th>
					<th style="width: 10%">'.$this->l('Image').'</th>
					<th style="width: 10%">'.$this->l('Action').'</th>
				</tr>
			</thead>
			<tbody>';
		foreach($result as $item)
		{
			$html.='<tr>
						<td class="center"><input type="checkbox" class="noborder" value="'.$item['idchild'].'" name="id[]"></td>
						<td><img src="'.$item['urlimg'].'" style="max-width: 100px;"></td>
						<td><a href="'.Tools::safeOutput($_SERVER['REQUEST_URI'].'&idchild='.$item['id'].'&deletechild=1').'"><img title="Supprimer" alt="Supprimer" src="../img/admin/delete.gif"></a></td>
					</tr>';
		}
		$html.='</tbody></table>';
		return $html;
	}

	private function _getData()
	{
		$sql='SELECT \'\' AS category,sl.idparent,name,listidcat '.
		' FROM '._DB_PREFIX_.'boxcategoryparent sl ';
		
		 return Db::getInstance()->ExecuteS($sql);
	}
	
	private function _getDataChild($idparent)
	{
		$sql='SELECT * '.
		' FROM '._DB_PREFIX_.'boxcategorychild WHERE idparent='.$idparent;
		return Db::getInstance()->ExecuteS($sql);
	}
	
	public function hookTop($params)
	{
		global $smarty, $cookie, $currentIndex;
		$listData=$this->_getData();
		foreach($listData as $key => $item)
		{
			$listData[$key]['category']=$this->_getDataChild($item['idparent']);
		}
		
		$smarty->assign(array(
			'listData'	=>	$listData
		));
		return $this->display(__FILE__, 'boxcategoryslide.tpl');
	}
	
	public function hookHeader()
	{
                Tools::addCSS($this->_path.'css/boxcategoryslide.css');
                Tools::addJS(($this->_path).'js/date.js');
                Tools::addJS(($this->_path).'js/jquery.idTabs.modified.js');  
	}
	
	public function getListCategory($listIdCat)
	{
		global $cookie;
		$sql='SELECT id_category,name FROM '._DB_PREFIX_.'category_lang WHERE id_category IN ('.$listIdCat.') AND id_lang='.$cookie->id_lang;
		$result=Db::getInstance()->ExecuteS($sql);
		$html='';
		foreach($result as $item)
			//$html.='<a href="'.Link::getCategoryLink($item['id_category']).'">'.$item['name'].'</a>';
                          $html.='<a href="javascript:show('.$item['id_category'].');">'.$item['name'].'</a>';
		return $html;
	}
	
	public function hookHome($params)
	{
		return $this->hookTop($params);
	}
}

?>